package com.gs.netty.support.resolver;

import com.alibaba.fastjson2.JSON;


import com.gs.netty.core.ResponseCode;
import com.gs.netty.core.SerializableEnum;
import com.gs.netty.core.annotation.CommandMapping;
import com.gs.netty.core.resolver.HandlerMethodReturnValueHandler;


import com.gs.netty.websocket.remoting.WebSocketInvocation;
import com.gs.netty.websocket.remoting.req.NativeWebSocketRequest;
import com.gs.netty.websocket.remoting.resp.AppResponse;
import org.springframework.core.MethodParameter;

import java.nio.charset.StandardCharsets;


public class JsonHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler<NativeWebSocketRequest> {


    public JsonHandlerMethodReturnValueHandler() {
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {

        CommandMapping methodAnnotation = returnType.getMethodAnnotation(CommandMapping.class);

        SerializableEnum serializable = methodAnnotation.serializable();

        return SerializableEnum.JSON.equals(serializable);
    }
    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, NativeWebSocketRequest request) {
        String body;
        if (returnValue instanceof CharSequence) {
            body = returnValue.toString();
        }else {
            body =  JSON.toJSONString(returnValue);
        }
        WebSocketInvocation appResponse = request.createResponse();
        appResponse.setStatus(ResponseCode.OK);

        appResponse.setPayload(body);
        // 写入数据
        request.getNativeResponse().writeAndFlush(appResponse);

    }
}
